<?php

namespace Theatre\Model;


class TicketAPI extends \Theatre\Model {
	/**
	 * Server Host
	 */
	private $server_host;


	/**
	 * The User id of the current logged in user
	 */
	private $user_id;


	/**
	 * The API Key
	 */
	private $api_key;


	/**
	 * The partner ID
	 */
	private $partner_id;


	/**
	 * Use SSL
	 */
	private $use_ssl;


	/**
	 * Constructor
	 */
	function __construct($params = array()) {
		parent::__construct();

		// Server Host
		if (empty($params['server_host'])) {
			throw new \Exception('Server Host required');
		}

		// API_KEY
		if (empty($params['api_key'])) {
			throw new \Exception('API Key required');
		}

		// PARTNER_ID
		if (empty($params['partner_id'])) {
			throw new \Exception('Partner ID required');
		}

		// USER_ID
		if (empty($params['user_id'])) {
			throw new \Exception('User ID required');
		}


		$this->user_id     = $params['user_id'];
		$this->api_key     = $params['api_key'];
		$this->partner_id  = $params['partner_id'];
		$this->server_host = $params['server_host'];
		$this->use_ssl     = empty($params['use_ssl']) ? false : true;
	}


	/**
	 * Get the schedule for the selected date
	 *
	 * @param string $date
	 */
	public function getShowSchedule($date = null) {
		$data = array(
			'date' => date('Y-m-d', (!$date ? time() : strtotime($date)))
		);

		return $this->_call($data, '/theatre/getSchedule', 'GET');
	}


	/**
	 * Get the seats status for the specified hall and show
	 */
	public function getAllSeats($hallId, $showId, $representationId, $date) {
		$data = array(
			'hall_id'           => $hallId,
			'show_id'           => $showId,
			'representation_id' => $representationId,
			'date'              => $date,
		);

		return $this->_call($data, '/show/getAllSeats', 'GET');
	}


	/**
	 * Get number of seats for the specified hall and show
	 */
	public function getSeats($hallId, $showId, $representationId, $seatNo, $seat_exception = array()) {
		foreach ($seat_exception as $index => $seat) {
			$seat_exception[$index] = "{$seat}";
		}

		// date
		$data = array(
			'hall_id'           => $hallId,
			'show_id'           => $showId,
			'representation_id' => $representationId,
			'seat_no'           => $seatNo,
			'request_seats'     => '1'
		);

		if (!empty($seat_exception)) {
			$data['seat_exception'] = $seat_exception;
		}

		return $this->_call($data, '/ticket/booking', 'GET');
	}


	/**
	 * Book the seats
	 */
	public function bookSeats($hallId, $showId, $representationId, $name) {
		$data = array(
			'hall_id'           => $hallId,
			'show_id'           => $showId,
			'representation_id' => $representationId,
			'name'              => $name
		);

		//return $this->_call($data, '/ticket/booking', 'POST');
		return $this->_call($data, '/ticket/booking', 'GET');
	}


	/**
	 * Make a call to the server
	 */
	private function _call($data, $url, $method = 'GET') {
		$data = $this->secureData($data);

		$curlHandle = curl_init();

		$scheme = empty($this->use_ssl) ? 'http' : 'https';

		$curlOpts = array(
			CURLOPT_URL              => $scheme . '://' . $this->server_host . $url,
			CURLOPT_HEADER           => false,
			CURLOPT_RETURNTRANSFER   => true,
			CURLOPT_SSL_VERIFYPEER   => false,
			CURLOPT_SSL_VERIFYHOST   => 2,
			CURLOPT_FOLLOWLOCATION   => true,
			CURLOPT_CONNECTTIMEOUT   => 60,
			CURLOPT_VERBOSE          => false,
			CURLOPT_NOSIGNAL         => true,
			CURLOPT_HTTPHEADER       => array(
				'Content-Type: application/json'
			)
		);

		if ($method == 'POST') {
			$curlOpts[CURLOPT_POSTFIELDS] = $data;
			$curlOpts[CURLOPT_POST]       = 1;
		}
		else {
			$curlOpts[CURLOPT_URL] .= '?' . http_build_query($data);
		}

		curl_setopt_array($curlHandle, $curlOpts);

		$curlMultiHandle = curl_multi_init();
		curl_multi_add_handle($curlMultiHandle, $curlHandle);

		do {
			$status = curl_multi_exec($curlMultiHandle, $active);
		}  while ($status == CURLM_CALL_MULTI_PERFORM);

		while ($active && $status == CURLM_OK) {
			if (($result = curl_multi_select($curlMultiHandle, 1)) != -1) {
				do {
					$status = curl_multi_exec($curlMultiHandle, $active);
				} while ($status == CURLM_CALL_MULTI_PERFORM);
			}
		}

		curl_multi_remove_handle($curlMultiHandle, $curlHandle);
		curl_multi_close($curlMultiHandle);

		$response = curl_multi_getcontent($curlHandle);
		$headers  = curl_getinfo($curlHandle);

		$json = json_decode($response, true);

		if ($json) {
			return (array)$json;
		}

		return null;
	}


	/**
	 * Secure the sent data
	 */
	private function secureData($data) {
		$now = time();

		$data['user_id']    = $this->user_id;
		$data['partner_id'] = $this->partner_id;
		$data['hash']       = hash_hmac('sha1', json_encode($data) . $now . $data['user_id'] . $data['partner_id'], $this->api_key);
		$data['time']       = $now;

		return $data;
	}
}
